import 'package:flutter/foundation.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';

class UserWallet {
  final String? id;
  final String? userId;
  final String? balance;
  final String? createTime;
  final String? updateTime;

  UserWallet({
    this.id,
    this.userId,
    this.balance,
    this.createTime,
    this.updateTime,
  });

  factory UserWallet.fromJson(Map<String, dynamic> json) {
    return UserWallet(
      id: json['id'],
      userId: json['userId'],
      balance: json['balance'],
      createTime: json['createTime'],
      updateTime: json['updateTime'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'balance': balance,
      'createTime': createTime,
      'updateTime': updateTime,
    };
  }
}

class UserWalletModel extends ChangeNotifier {
  UserWallet? _wallet;
  bool _isLoading = false;
  String _errorMessage = '';

  UserWallet? get wallet => _wallet;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  bool get hasWallet => _wallet != null;
  String? get balance => _wallet?.balance; // 修改为返回 String? 类型
  double get balanceAsDouble => double.tryParse(_wallet?.balance ?? '0') ?? 0.0; // 添加新的 double 类型 getter

  // 加载用户钱包信息
  Future<void> loadWallet(GraphQLClient client) async {
    try {
      _isLoading = true;
      _errorMessage = '';
      notifyListeners();

      final result = await client.query(
        QueryOptions(
          document: gql(UserGQL.fetchUserWallet),
        ),
      );

      if (result.hasException) {
        _errorMessage = '加载钱包信息失败: ${result.exception.toString()}';
        debugPrint('加载钱包信息失败: ${result.exception.toString()}');
      } else {
        final walletData = result.data!['user']['currentUser']['wallet'];
        if (walletData != null) {
          _wallet = UserWallet.fromJson(walletData);
        } else {
          _wallet = null;
        }
        _errorMessage = '';
      }
    } catch (e) {
      _errorMessage = '加载钱包信息异常: $e';
      debugPrint('加载钱包信息异常: $e');
    } finally {
      _isLoading = false;
      Future.microtask(() => notifyListeners());
    }
  }

  // 开通钱包
  Future<bool> openWallet(GraphQLClient client, {required String payPassword}) async {
    try {
      final result = await client.mutate(
        MutationOptions(
          document: gql(UserGQL.fetchUserOpenWallet),
          variables: {
            'payPassword': payPassword,
          },
        ),
      );

      if (result.hasException) {
        _errorMessage = '开通钱包失败: ${result.exception.toString()}';
        debugPrint('开通钱包失败: ${result.exception.toString()}');
        notifyListeners();
        return false;
      } else {
        final walletData = result.data!['user']['openCurrentUserWallet'];
        _wallet = UserWallet.fromJson(walletData);
        _errorMessage = '';
        notifyListeners();
        return true;
      }
    } catch (e) {
      _errorMessage = '开通钱包异常: $e';
      debugPrint('开通钱包异常: $e');
      notifyListeners();
      return false;
    }
  }

  // 钱包充值
  Future<bool> rechargeWallet(GraphQLClient client, {
    required String amount,
    required String channelType,
    required String channelId,
    required String payPassword,
  }) async {
    try {
      final result = await client.mutate(
        MutationOptions(
          document: gql(UserGQL.fetchUserWalletRecharge),
          variables: {
            'amount': amount,
            'channelType': channelType,
            'channelId': channelId,
            'payPassword1': payPassword,
          },
        ),
      );

      if (result.hasException) {
        _errorMessage = '充值失败: ${result.exception.toString()}';
        debugPrint('充值失败: ${result.exception.toString()}');
        notifyListeners();
        return false;
      } else {
        final walletData = result.data!['user']['rechargeCurrentUserWallet'];
        _wallet = UserWallet.fromJson(walletData);
        _errorMessage = '';
        notifyListeners();
        return true;
      }
    } catch (e) {
      _errorMessage = '充值异常: $e';
      debugPrint('充值异常: $e');
      notifyListeners();
      return false;
    }
  }

  // 清空钱包信息
  void clearWallet() {
    _wallet = null;
    notifyListeners();
  }
}